import React, { useRef, useState, useEffect, useCallback } from 'react';
import { Button, message, Modal, Tabs, Tooltip, Empty, Tag } from 'antd';

import { getSoundTempList, deleteSoundTemp } from 'admin/servers/servers';

import SoundTempPop from './components/SoundTempPop';

import { CloseCircleFilled, EditFilled } from '@ant-design/icons';
import { SoundTempInfo } from 'admin/schema/SoundLibrary';
import SoundList from './components/SoundList';
import { clearNull } from 'utils/tools';
import './style.scss';

const { TabPane } = Tabs;

/**
 * 录音库
 * AI管理-机器人管理-版本管理-配置话术流程-录音库-入参-versionId
 * AI管理-通知流程管理-录音库-入参-notifyFlowId
 * versionId和notifyFlowId,二者必须传一个
 */

const SoundLibrary: React.FC<{ versionId?: number; notifyFlowId?: number }> = ({
  versionId,
  notifyFlowId,
}) => {
  /**
   * 新增、编辑弹窗-ref
   */
  const childRef = useRef();
  const [panes, setPanes] = useState<Array<any>>([]); // 模板标签卡
  const [activeKey, setActiveKey] = useState<string>(); //当前tab标签卡
  const [soundType, setSoundType] = useState<'ai' | 'notice'>('ai'); //录音库类型
  /**
   * 模板：获取列表
   */
  const initPanesList = useCallback(async () => {
    if (versionId) {
      setSoundType('ai');
    }
    if (notifyFlowId) {
      setSoundType('notice');
    }
    console.log('录音模板列表-数据-请求');
    try {
      const res = await getSoundTempList(
        clearNull({
          versionId,
          notifyFlowId,
          pageNo: 1,
          pageSize: 10000,
        })
      );
      const { code, data } = res;

      if (code === 0) {
        if (data && data.length) {
          // 列表-非空展示
          setPanes(data);
          // 默认选中第一个tab
          const firstKey = 'sound-list-tab' + data[0].templateId;
          setActiveKey(firstKey);
        } else {
          setPanes([]);
        }
      }
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
  }, [notifyFlowId, versionId]);

  useEffect(() => {
    initPanesList();
  }, [initPanesList]);
  /**
   * 模板：新增-操作
   */
  const handleAdd = () => {
    console.log('新增tab');
    (childRef.current as any).open({ versionId, notifyFlowId }, () => {
      // 回调函数：添加成功，刷新tab列表
      initPanesList();
    });
  };

  /**
   * 模板：修改-操作
   */
  const handleEdit = (pane: SoundTempInfo) => {
    console.log(pane.templateId, '编辑tab');
    (childRef.current as any).open(pane, () => {
      // 回调函数：编辑成功，刷新tab列表
      initPanesList();
    });
  };

  /**
   * 模板：删除-操作
   */
  const handleDelete = (pane: SoundTempInfo) => {
    Modal.confirm({
      title: '删除模板提示',
      content: '删除后无法恢复! 确认删除吗?',
      async onOk() {
        try {
          const res = await deleteSoundTemp(pane.templateId);
          if (res.code === 0) {
            message.success(`删除成功`);
            // 刷新tab列表
            initPanesList();
          } else {
            message.error(`${res.tips}(错误码: ${res.code})`);
          }
        } catch (error) {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        }
      },
    });
  };
  return (
    <div className="soundlibrary">
      <Tabs
        tabPosition="left"
        tabBarGutter={8}
        onChange={activeKey => {
          // 切换标签tab
          console.log(activeKey, '当前选择的tap');
          setActiveKey(activeKey);
        }}
        activeKey={activeKey}
        type="card"
        tabBarExtraContent={
          <Button type="primary" className="tab-add" onClick={() => handleAdd()}>
            添加录音模板
          </Button>
        }
      >
        {panes.length > 0 &&
          panes.map(pane => (
            <TabPane
              key={'sound-list-tab' + pane.templateId}
              className="tab-pane-content"
              tab={
                <div className="tab-pane">
                  <Tooltip title={pane.templateName} placement="topLeft">
                    <div className="pane-name ellipsis">{pane.templateName}</div>
                  </Tooltip>
                  <div className="line">
                    {pane.templateStatus ? (
                      <Tag color="success">已完成</Tag>
                    ) : (
                      <Tag color="error">待录音</Tag>
                    )}
                    {pane.ownerShip >= 0 && (
                      <Tag color="blue">{pane.ownerShip ? '个人' : '公共'}</Tag>
                    )}
                  </div>
                  {!!pane.nickName && (
                    <div className="line">
                      <Tooltip title={pane.nickName} placement="topLeft">
                        <Tag color="cyan" className="create-name  ellipsis">
                          {pane.nickName}
                        </Tag>
                      </Tooltip>
                    </div>
                  )}
                  <Tooltip placement="right" title="编辑模板">
                    <Button className="tab-edit" type="link" onClick={() => handleEdit(pane)}>
                      <EditFilled />
                    </Button>
                  </Tooltip>
                  <Tooltip placement="right" title="删除模板">
                    <Button className="tab-remove" type="link" onClick={() => handleDelete(pane)}>
                      <CloseCircleFilled />
                    </Button>
                  </Tooltip>
                </div>
              }
            >
              {!!activeKey && (
                <div className="tab-wrap">
                  <SoundList
                    type={soundType}
                    templateId={pane.templateId}
                    containVar={pane.containVar}
                    refreshPane={initPanesList}
                  />
                </div>
              )}
            </TabPane>
          ))}
      </Tabs>
      {!panes.length && (
        <div className="empty-wrap">
          <Empty
            className="special-empty"
            image="/webapp/no-pie-data.png"
            imageStyle={{ height: 300, margin: 20, paddingRight: 10 }}
            description="请先添加录音模板"
          >
            <Button type="primary" className="tab-add" onClick={() => handleAdd()}>
              添加录音模板
            </Button>
          </Empty>
        </div>
      )}
      {/* 新增编辑弹窗 */}
      <SoundTempPop cRef={childRef}></SoundTempPop>
    </div>
  );
};

export default SoundLibrary;
